<template>
  <div class="cpt-coding-loginmodal  cpt-coding-loginmodal-ai">
    <el-dialog v-model="loginModalVisible" title="" class="commdialog-1">
      <div class="dialogcon-login dialogcon-login-ai flex rounded-2xl box-border p-0">
        <div class="left p-t-8 2xl:p-t-10">
          <div class="logo h-8 2xl:h-10 bg-contain bg-no-repeat bg-center" style="
              background-image: url('https://cdn.codinghou.cn/coding/pc-ai/icons/login-logo1.png');
            "></div>
          <div class="text m-t-6 p-t-3 box-border p-l-10 2xl:p-l-25 text-4 2xl:text-5 text-white text-left">

            <div class="">
              学习伙伴：个性化作业辅导神器
            </div>

            <div class="mb-2 mt-2">
              生活伙伴：解答疑惑，时刻陪伴
            </div>

            <div class="">
              工作伙伴：各类工具提高工作效率
            </div>

          </div>
          <div
            class="qrcode flex items-center justify-between mx-auto m-t-10 w-50 2xl:w-60 h-60 2xl:h-70 bg-contain bg-center bg-no-repeat"
            style="
              background-image: url('https://cdn.codinghou.cn/coding/qrcode/codinghou2021.png');
            "></div>
        </div>
        <div class="right p-t-10 p-l-10 2xl:p-t-20 2xl:p-l-20" v-if="tabIndex == 0">
          <div class="text-bold text-center text-black-[#4A4A4A] text-xl 2xl:text-2xl">
            欢迎回来
          </div>
          <el-form>
            <div class="form form1 m-t-5">
              <div class="uesrname line">
                <div class="label">账号：</div>
                <div class="input">
                  <input type="text" placeholder="请输入账号" v-model="username" autocomplete="on" />
                </div>
              </div>
              <div class="password line">
                <div class="label">密码</div>
                <div class="input">
                  <input :type="passwordType" placeholder="请输入密码" @keyup.enter="loginByAccount" v-model="password"
                    autocomplete="on" />
                  <div class="btn btn-view" v-if="!passwordVisible" @click="passwordVisible = !passwordVisible">
                    <el-icon color="#fff">
                      <ElIconView />
                    </el-icon>
                  </div>
                  <div class="btn btn-hidden" v-else @click="passwordVisible = !passwordVisible">
                    <el-icon color="#fff">
                      <ElIconHide />
                    </el-icon>
                  </div>
                </div>
              </div>
              <div class="btncon">
                <div class="btn-login" v-loading="loading" @click="loginByAccount">
                  点击登录
                </div>
              </div>
            </div>
          </el-form>

          <div class="switchtab" @click="tabIndex = 1">
            <span class="text">还没有账号？</span>
            <span class="tablink">前往注册</span>
          </div>
          <div class="tip">
            <!-- 如没有账号或者忘记密码，请微信联系侯老师 -->
            <p>(←如遇到问题请微信扫描左侧二维码联系侯老师)</p>
            <!-- <p>( ←微信扫描左侧二维码或者微信添加<span class="wechat">codinghou001</span> 好友)</p> -->
          </div>
        </div>
        <div class="right p-t-10 p-l-10 2xl:p-t-20 2xl:p-l-20 right2" v-if="tabIndex == 1">
          <div class="text-bold text-center text-black-[#4A4A4A] text-xl 2xl:text-2xl">
            注册
          </div>
          <div class="form form2 m-t-5">
            <div class="uesrname line">
              <div class="label">账号：</div>
              <div class="input">
                <input type="text" placeholder="账号，请输入4~16位字母、数字" v-model="reUsername" />
              </div>
            </div>
            <div class="errortip" v-if="reUsernameErrMsg">
              {{ reUsernameErrMsg }}
            </div>

            <div class="password line">
              <div class="label">密码</div>
              <div class="input">
                <input type="password" placeholder="密码，6~16位密码" v-model="rePassowrd" />
              </div>
            </div>
            <div class="errortip" v-if="rePassowrdErrMsg">
              {{ rePassowrdErrMsg }}
            </div>
            <div class="password line">
              <div class="label">昵称</div>
              <div class="input">
                <input type="text" placeholder="昵称" v-model="reNickname" />
              </div>
            </div>
            <div class="errortip" v-if="reNicknameErrMsg">
              {{ reNicknameErrMsg }}
            </div>
            <div class="password line" v-show="false">
              <div class="label">邀请码</div>
              <div class="input">
                <input type="text" placeholder="邀请码" v-model="beInvitedCode" />
              </div>
            </div>
            <div class="errortip" v-if="beInvitedCodeErrMsg">
              {{ beInvitedCodeErrMsg }}
            </div>
            <div class="btncon">
              <div class="btn-login" @click="register">点击注册</div>
            </div>
            <div class="switchtab" @click="tabIndex = 0">
              <span class="text">已有账号？</span>
              <span class="tablink">立即登录</span>
            </div>
            <div class="tip">

              <p>如果有侯老师编程网站账号，也可直接登录</p>

              <!-- <p>( ←微信扫描左侧二维码或者微信添加<span class="wechat">codinghou001</span> 好友)</p> -->
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>

</template>
<script lang="ts" setup>



import { storeToRefs } from "pinia";

import { useAppStore } from "~/stores/app";
import { postUserRegister, postUserLoginByAccount } from "~/service/yapi";
import storage from "~/utils/storage";
const toastOpen = ref(false)


const { signIn, token, data, status, lastRefreshedAt, signOut, getSession } =
  useAuth();

let app = useAppStore();
const { loginModalVisible } = storeToRefs(app);
const { toggleLoginModal } = app;

let username = ref("");
let password = ref("");
let reUsername = ref("");
let reUsernameErrMsg = ref("");
let rePassowrd = ref("");
let rePassowrdErrMsg = ref("");
let reNickname = ref("");
let reNicknameErrMsg = ref("");
let beInvitedCode = ref("momoai");
let beInvitedCodeErrMsg = ref("");
let tabIndex = ref(0);
let loading = ref(false);
let passwordVisible = ref(false);
let passwordType = computed(() => {
  return passwordVisible.value ? "text" : "password";
});
function handleClose() {
  toggleLoginModal();
}
function countChineseCharacters(str: any) {
  const pattern = /[\u4e00-\u9fa5]/g;
  const matches = str.match(pattern);
  return matches ? matches.length : 0;
}
async function register() {
  reUsername.value = reUsername.value.replace(/\s*/g, "");
  rePassowrd.value = rePassowrd.value.replace(/\s*/g, "");
  reUsernameErrMsg.value = "";
  rePassowrdErrMsg.value = "";
  reNicknameErrMsg.value = "";
  beInvitedCodeErrMsg.value = "";
  if (!reUsername.value) {
    return (reUsernameErrMsg.value = "账号不能为空");
  }
  if (countChineseCharacters(reUsername.value) > 2) {

  } else if (reUsername.value.length < 4 || reUsername.value.length > 16) {
    return (reUsernameErrMsg.value = "账号长度有误");
  }
  if (!rePassowrd.value) {
    return (rePassowrdErrMsg.value = "密码不能为空");
  }
  if (rePassowrd.value.length < 6) {
    return (rePassowrdErrMsg.value = "密码长度不能低于6位");
  }
  if (!reNickname.value) {
    return (reNicknameErrMsg.value = "昵称不能为空");
  }
  if (!beInvitedCode.value) {
    return (beInvitedCodeErrMsg.value = "邀请码不能为空");
  }
  beInvitedCode.value = beInvitedCode.value.replace(/\s*/g, "");
  postUserRegister({
    username: reUsername.value,
    password: rePassowrd.value,
    nickname: reNickname.value,
    beInvitedCode: beInvitedCode.value,
  })
    .then((res: any) => {
      if (res.code == 1000) {
        username.value = reUsername.value;
        password.value = rePassowrd.value;
        ElMessage.success("注册成功，快去创作吧");
        tabIndex.value = 0;
      } else {
        ElMessage.warning(res.message);
      }
    })
    .catch((err) => {
      ElMessage.warning(err);
    });
}
let route = useRoute();

async function loginByAccount() {
  if (loading.value) {
    return;
  }
  loading.value = true;
  try {
    let res: any = await postUserLoginByAccount({
      username: username.value,
      password: password.value,
    });
    toastOpen.value = true
    if (res.code == 20003) {
      loading.value = false;

      ElMessage.warning("账号已被禁用，请联系管理员");

      return;
    }
  } catch (error) {
    loading.value = false;
    console.log(error);
    return ElMessage.warning("用户名或密码错误");
  }

  signIn(
    { username: username.value, password: password.value },
    { callbackUrl: route.path }
  )
    .then((res) => {
      let { expire, refreshExpire, accessToken, refreshToken } = res;

      let rawToken = token.value?.replace("Bearer ", "");

      storage.set("token", rawToken);

      // // 刷新 token 的唯一标识
      // storage.set("refreshToken", refreshToken, refreshExpire);
      loading.value = false;
      ElMessage.success("登录成功 ");
      toggleLoginModal();
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.warning("用户名或密码错误");
    });
}
</script>
<style lang="scss">
.dialogcon-login {
  @apply w-189 h-134 bg-[var(--black-light)] rounded-2xl;



  &.dialogcon-login-ai {
    background: #F7F7F7;

    .left {
      background: linear-gradient(180deg, #368298 0%, #88B9C8 100%);
      border-radius: 10px 0px 0px 10px;
    }

    .right {
      background: #F7F7F7;

      .form {
        .line {

          @apply bg-white;

          input {

            @apply text-black-[#4A4A4A] bg-white;
          }

          input::-webkit-input-placeholder {
            color: rgba(0, 0, 0, 0.45);
          }

          .input {
            @apply w-40 text-black-[#4A4A4A] border-none;

          }

        }
      }

      .btn-login {
        background: linear-gradient(180deg, #F5D491 0%, #FFC845 100%);
        border: 1.6px solid #EFBA56;

      }

    }
  }

  .left {
    @apply flex-none w-81 bg-[var(--black-base)] rounded-2xl;
  }

  .right {
    @apply bg-[var(--black-light)];

    .form {
      .line {
        @apply bg-[#323232] flex text-5 items-[flex-end] m-b-2 w-87;


        .label {
          @apply text-4.5 text-gray-300 w-20 hidden;
        }

        input {
          @apply border-none bg-transparent line-height-8 p-l-2 w-87 h-12 bg-[#323232] rounded-2xl opacity-100 text-4.5 text-black-[#4A4A4A] box-border;

        }

        input:focus {
          outline: none;
        }

        input::-webkit-input-placeholder {
          color: rgba(255, 255, 255, 0.45);
        }

        .input {
          @apply w-40 text-black-[#4A4A4A] border-none;

        }
      }

      .password {
        .input {
          @apply relative w-full;

          .btn {
            @apply absolute right-2 top-2 text-5;
          }
        }
      }

      .btn-login {
        @apply text-black-[#4A4A4A] text-center w-87 h-12 bg-[#755afb] line-height-12 rounded-2xl text-4.5 cursor-pointer mt-4;
      }

      .errortip {
        @apply text-red-600 mb-2;
      }
    }

    .switchtab {
      @apply mb-9 text-center text-black-[#4A4A4A] opacity-65 text-4.5 mt-2;

      .tablink {
        @apply text-purple-600 cursor-pointer;
      }
    }

    .tip {
      text-align: left;
      color: #fff;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.45);

      .wechat {
        font-weight: bold;
      }

      p {
        padding-top: 10px;
        font-size: 14px;
        color: rgba(255, 255, 255, 0.45);
      }
    }
  }

  .right2 {
    padding-top: 20px;

    .line {
      position: relative;

      &::before {
        content: "*";
        color: var(--red);
        position: absolute;
        left: -20px;
        top: 15px;
      }
    }

    .switchtab {
      margin-bottom: 20px;
    }
  }
}

@media only screen and (min-width: 1536px) {
  .dialogcon-login {
    @apply w-283 h-180;

    .left {
      @apply flex-none w-121;
    }

    .right {
      @apply flex-none w-160;


      .form {
        .line {
          @apply w-116 line-height-10 mb-5;

          input {
            @apply w-116;
          }

          .input {
            @apply w-116;
          }
        }

        .btn-login {
          @apply w-116 h-15 line-height-15 mt-6;
        }
      }

      .switchtab {
        @apply w-91;
      }

      .tip {
        @apply text-4;

        p {
          @apply text-4;

        }
      }
    }
  }
}
</style>
